<?php
namespace app\faxing\channel;


use app\common\model\Gameulog;
use app\common\model\Order;
use app\common\model\Player;
use app\common\model\PlayerRole;
use app\index\controller\Exception;
use think\cache\driver\Redis;
use think\Db;
use think\facade\Log;
use think\facade\Session;
use app\common\controller\FaXingBase;

/**
 * 后台首页
 * Class Index
 * @package app\admin\controller
 */
class Yuewen extends FaXingBase
{

    public function register($params)
    {
        $cid = $this->cid;
        $sign = $params['flag'];

        $check_sign = md5($params['username'].$params['serverid'].$params['timestamp'].
            $this->extdata['APPKEY'].$params['clientid']);

        if($check_sign != $sign){
            $this->error("签名错误");
        }

        $account = $cid."_".$params['username'];
        $player = Player::getOne(['account'=>$account]);
        if(!$player){
            //注册
            $data['account'] = $account;
            $data['password'] = get_encrypt('123456');
            $data['type'] = 0;
            $data['cid'] = $this->cid;
            $data['gid'] = $this->gid;
            $data['is_age'] = 0;
            if($params['isadult'] == 1){
                $data['is_age'] = 2;
            }
            if($params['isadult'] == 2){
                $data['is_age'] = 1;
            }

            try {
                Db::startTrans();
                $player = Player::register($data);
                Db::commit();
            }catch (Exception $e) {
                Db::rollback();
                $this->error("登录失败，请稍后再试。");
                Log::info("用户注册失败:".$e->getMessage());
            }
        }
        $game = $this->game;
        $data['uid'] = $player['id'];
        //记录登录信息
        Gameulog::addLog($data);
        $token = get_encrypt($data['uid']);
        $player['token'] = $token;
        unset($player['password']);
        $player['third_data'] = $params;
        Session::set('palyerinfo', json_encode($player));
        //redis 保存用户信息
        $redis = new Redis();
        $redis->set($token, $player);

        if (strpos($game['api_login_url'], '?') !== false) {
            $game_url = $game['api_login_url']."&token=".$token;
        } else {
            $game_url = $game['api_login_url']."?token=".$token;
        }
        return ['game_url'=>$game_url,'token'=>$token];

    }


    public function order($order)
    {
        $role = PlayerRole::where(['gid'=>$order['gid'],'uid'=>$order['uid'],'cid'=>$order['cid']])->find();
        $data = [
            'serverid'=> (int) $role['sid'],//区服id
            'orderid' => $order['order_no'],// 游戏方订单号
            'money'=> $order['amount'],//金额 整数：分
            'goodname'=>$order['goods_name'],//商品名称
        ];
        return $data;
    }

    public function check_order($params)
    {
        $order_no = $params['gorderid'];
        $sign = $params['flag'];


        // 查询订单
        $order = Order::where([
            'order_no'=>$order_no
        ])->find();

        if(!$this->check_sign($params,$this->extdata['APPKEY'])){
            echo json_encode(['ReturnCode'=>-1,'message'=>'签名错误']);exit;
        }

        if($order['amount'] != $params['money']){
            echo json_encode(['code'=>-2,'message'=>'处理失败']);exit;
        }

        $order->trade_no = $params['orderid'];
        $order->save();

        return $order;
    }

    public function create_role($params)
    {
        $url = "https://api2-game.qidian.com/Home/Ly/roleReport?data=";

        $redis = new Redis();
        $player = $redis->get($params['token']);
        $third_data = $player['third_data'];
        $account = explode("_",$player['account']);
        $time = time();
        $data = [
            'userId' => (int) $account[1],
            'gameId' => (int) $this->extdata['game_id'],
            'serverId' =>(int) $params['sid'],
            'roleId' => $params['role_id'],
            'roleName' =>  $params['role_name'],
            'createRoleTime' => $time,
            'time' => $time,
        ];
        ksort($data);
        $signStr = http_build_query($data) . "&key=".$this->extdata['APPKEY'];

        $data['sign'] =  md5(md5($signStr));
        ksort($data);

        $res = file_get_contents($url.base64_encode(http_build_query($data)));
        echo $res['data'];exit;
    }


    public function message($message,$order)
    {
        echo $message === 'success' ? json_encode(['ReturnCode'=>0,'message'=>'成功']) :  json_encode(['code'=>'-1','message'=>'处理失败']);
        exit;
    }


    protected function check_sign($params, $key)
    {
        $sign = $params['sign'];
        $check_sign = md5($params['username'].$params['serverid'].$params['clientid'].$params['orderid'].
            $params['timestamp'].$params['itemid'].$params['money'].$key);

        if($check_sign != $sign){
            return false;
        }
        return true;
    }

}